package org.clipjoint.controller;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import org.clipjoint.entity.EmailCode;
import org.clipjoint.service.UserService;
import org.clipjoint.service.impl.UserServiceImpl;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/email")
public class EmailController extends HttpServlet {
	private static final long serialVersionUID = 5L;
	
	private UserService userService = new UserServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method = request.getParameter("method");
		switch (method) {
		case "sendRegisterCode":
			sendRegisterCode(request, response);
			break;
		default:
			break;
		}
		
	}
	
	// 注册时发送的邮箱验证码
	private void sendRegisterCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		// 获取邮箱地址
		String email = request.getParameter("email");
		
		// 查询是否有该邮箱的用户
		boolean result = true;
		try {
			result = userService.checkEmail(email);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 如果result是false，说明数据库有该邮箱
		if (result) {
			// 随机生成验证码
			String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
			request.getSession().setAttribute("emailRegisterCode", EmailCode.builder().email(email).code(code).build());
			
			// 发送邮件
			MailUtil.send(email, "极光游戏平台邮箱验证码", code, false);
			
			response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(0).msg("邮件发送成功！").build()));
		} else {
			response.getWriter().print(JSON.toJSONString(JsonResult.builder().code(1).msg("该邮箱已注册！").build()));
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
